<?php

namespace app\cps\service;

use app\model\OfficialAccounts;
use app\common\Common;
use app\model\CustomReply;
use app\model\KeywordReply;
use app\model\PayRecord;
use app\model\CustomMenu;
use app\model\Videos;
use app\model\Applet;
use app\common\Error;
use app\model\ResponsibilityPerson;

class OfficialAccountService
{
    private $model;
    private $customReplyModel;
    private $keywordReplyModel;
    private $payRecordModel;
    private $customMenuModel;
    private $videosModel;
    private $appletModel;
    private $responsibilityPersonModel;

    public function __construct(OfficialAccounts $model, CustomReply $customReplyModel, KeywordReply $keywordReplyModel, PayRecord $payRecordModel, CustomMenu $customMenuModel, Videos $videosModel, Applet $appletModel, ResponsibilityPerson $responsibilityPersonModel)
    {
        $this->model = $model;
        $this->customReplyModel = $customReplyModel;
        $this->keywordReplyModel = $keywordReplyModel;
        $this->payRecordModel = $payRecordModel;
        $this->customMenuModel = $customMenuModel;
        $this->videosModel = $videosModel;
        $this->appletModel = $appletModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
    }

    // 获取公众号详情
    public function getOfficialAccountDetail($userInfo)
    {
        $id = $userInfo['cps_used_official_account_id'];
        $data = $this->model->getInfoById($id, 'id, type, is_auth, original_id, wechat_number, name, app_id, app_secret');

        $data['ip_white_list'] = config('enum.ip');

        return $data;
    }

    // 公众号信息设置
    public function officialAccountSetting($params, $userInfo)
    {
        $params['updated_at'] = time();
        $params['responsibility_person_id'] = $userInfo['cps_user_id'];

        $id = $this->model->edit($params);

        if (!$id) {
            return [];
        }

        $data = $this->model->getInfoById($params['id'], 'id, type, is_auth, original_id, wechat_number, name, app_id, app_secret');

        $data['ip_white_list'] = config('enum.ip');

        return $data;
    }

    /**
     * 自动回复设置
     * 
     * @param type 1关注 2签到
     * @return array
     * */
    public function autoReplySetting($params, $userInfo)
    {
        if ($params['link_url'] == 'link'){
            $params['link_url'] = $params['link'];
        }

        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $data = $this->customReplyModel->getInfoByWhere(['official_account_id' => $officialAccountId, 'type' => $params['type']], 'id');

        if ($data) {
            // 修改
            $saveData = [
                'id' => $data['id'],
                'official_account_id' => $officialAccountId,
                'responsibility_person_id' => $userInfo['cps_user_id'],
                'type' => $params['type'],
                'title' => $params['title'],
                'link_url' => $params['link_url'],
                'updated_at' => time()
            ];
        } else {
            // 添加
            $saveData = [
                'official_account_id' => $officialAccountId,
                'responsibility_person_id' => $userInfo['cps_user_id'],
                'type' => $params['type'],
                'title' => $params['title'],
                'link_url' => $params['link_url'],
                'created_at' => time()
            ];
        }

        if (!empty($params['up_text'])) {
            $saveData['up_text'] = $params['up_text'];
        }

        if (!empty($params['down_text'])) {
            $saveData['down_text'] = $params['down_text'];
        }

        $id = $this->customReplyModel->edit($saveData);

        if (!$id) {
            return [];
        }

        $result = $this->customReplyModel->getInfoById($id, 'id, type, up_text, down_text, title, link_url');

        return $result;
    }

    // 关键字回复列表
    public function keywordReplyList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $officialAccountId = $userInfo['cps_used_official_account_id'];
        $where[] = ['official_account_id', '=', $officialAccountId];

        // 关键字搜索
        if (!empty($params['keyword'])) {
            $where[] = ['keyword', 'like', '%' . $params['keyword'] . '%'];
        }

        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        $data = $this->keywordReplyModel->getPagingDataByWhere($where, $page, $limit, 'id, keyword, type, watch_num, order_amount, created_at');

        return $data;
    }

    // 关键字回复详情
    public function getKeywordReplyDetail(int $id)
    {
        $data = $this->keywordReplyModel->getInfoById($id, 'id, keyword, type, link_type, video_id, title, cover, link_url, up_text, down_text, media_id');

        return $data;
    }

    // 添加/编辑关键字回复
    public function editKeywordReply(array $params, $userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];

        if (empty($params['id'])) {
            $params['official_account_id'] = $officialAccountId;
            $params['created_at'] = time();
        } else {
            $data = $this->keywordReplyModel->getInfoById($params['id'], 'official_account_id');

            if ($data['official_account_id'] != $officialAccountId) {
                return false;
            }
            $params['updated_at'] = time();
        }

        $params['responsibility_person_id'] = $userInfo['cps_user_id'];

        $id = $this->keywordReplyModel->edit($params);

        return $id ? true : false;
    }

    // 获取指定关键字产生的订单列表
    public function getKeywordReplyOrderList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 1;
        $where[] = ['interpolate_id', '=', $params['id']];

        // 商户单号搜索
        if (!empty($params['order_no'])) {
            $where[] = ['order_no', 'like', $params['order_no'].'%'];
        }

        // 交易单号搜索
        if (!empty($params['wechat_order_no'])) {
            $where[] = ['wechat_order_no', 'like', $params['wechat_order_no'].'%'];
        }

        // 充值金额搜索
        if (!empty($params['total_fee'])) {
            $where[] = ['total_fee', '=', $params['total_fee']];
        }

        // 支付状态搜索
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        // 下单时间搜索
        if (!empty($params['created_at'])) {
            $where[] = ['created_at', '>=', strtotime($params['created_at'].' 00:00:00')];
            $where[] = ['created_at', '<=', strtotime($params['created_at'].' 23:59:59')];
        }

        $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'id, order_no, wechat_order_no, uid, total_fee, type, status, created_at, pay_time, interpolate_id');

        return $data;
    }

    // 获取自定义的关注回复和签到回复
    public function getCustomReply($type, $userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];
        $officialAccountData = $this->model->getInfoById($officialAccountId, 'name, follow_reply_switch, sign_reply_switch');

        $data = $this->customReplyModel->getInfoByWhere(['type' => $type, 'official_account_id' => $officialAccountId], 'id, up_text, down_text, title, link_url');
        if (empty($data)){
            $data['link_url'] = '';
        }
        $data['follow_reply_switch'] = $officialAccountData['follow_reply_switch'];
        $data['sign_reply_switch'] = $officialAccountData['sign_reply_switch'];
        $data['name'] = $officialAccountData['name'];

        //如果链接以http开头，那就是投放链接
        if (isset($data['link_url']) && strpos( $data['link_url'],'http') === 0){
            $data['link'] = $data['link_url'];
            $data['link_url'] = 'link';
        }

        return $data;
    }

    // 回复开关设置
    public function replySwitchSetting($params, $userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];
        $value = $params['value'];

        if ($params['type'] == 1) {
            $this->model->where(['id' => $officialAccountId])->update(['follow_reply_switch' => $value]);
        } else {
            $this->model->where(['id' => $officialAccountId])->update(['sign_reply_switch' => $value]);
        }

        return $value;
    }

    // 获取自定义菜单设置
    public function getCustomMenuSet($userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $data = $this->customMenuModel->getInfoByWhere(['official_account_id' => $officialAccountId], 'id, content');
        if ($data && !empty($data['content'])) {
            $data['content'] = json_decode($data['content'], true);
        } else {
            $data['content'] = [];
        }
        $officialAccountData = $this->model->getInfoByWhere(['id' => $officialAccountId], 'id, name, content, original_id, token, app_id, app_secret, encoding_aes_key, applet_id');
        $appletData = $this->appletModel->getInfoById($officialAccountData['applet_id'], 'app_id');

        $data['applet_app_id'] = $appletData['app_id'];

        return $data;
    }

    // 自定义菜单设置
    public function customMenuSetting($params, $userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $data = $this->customMenuModel->getInfoByWhere(['official_account_id' => $officialAccountId], 'id, content');
        if (empty($params['id']) && $data) {
            return ['message' => Error::OFFICIAL_ACCOUNT_ALREADY_CUSTOM_MENU];
        }

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $pid = $params['pid'] ?? 0;

        $saveData = [
            'official_account_id' => $officialAccountId,
            'responsibility_person_id' => $responsibilityPersonId,
            'is_push' => empty($params['is_push']) ? 0 : 1,
            'content' => $params['content']
        ];

        if (empty($params['id'])) {
            $saveData['created_at'] = time();
        } else {
            $saveData['id'] = $params['id'];
            $saveData['updated_at'] = time();
        }

        if (!empty($params['is_push'])) {
            // 发布
            $officialAccountData = $this->model->getInfoById($officialAccountId, 'app_id, app_secret');
            $accessToken = Common::getWechatOfficialAccountAccessToken($officialAccountData['app_id'], $officialAccountData['app_secret'], $officialAccountId);
   

            $requestData = [];
            $button=json_decode($params['content'],true);
            if(empty($button['button'])){
                $url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$accessToken;
                $wechatResult = Common::curlRequest($url, 'POST', '');
            }else{

                $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$accessToken;
                $wechatResult = Common::curlRequest($url, 'POST', $params['content']);
            }

            $wechatResult = json_decode($wechatResult, true);
            if ($wechatResult['errcode']) {
                return ['message' => Error::MENU_PUSH_FAIL];
            }
        }

        $id = $this->customMenuModel->edit($saveData);

        return $id ? true : false;
    }

    // 上传素材
    public function uploadFileToWechat($file, $userInfo)
    {
        list($name, $suffix) = explode('.', $file['name']);
        $newName = time();
        move_uploaded_file($file['tmp_name'], 'uploads/material/' . $newName . '.' . $suffix);
        $filePath = realpath('uploads/material/' . $newName . '.' . $suffix);

        $officialAccountId = $userInfo['cps_used_official_account_id'];

        $officialAccountData = $this->model->getInfoById($officialAccountId, 'id, app_id, app_secret');
        $accessToken = Common::getWechatOfficialAccountAccessToken($officialAccountData['app_id'], $officialAccountData['app_secret'], $officialAccountData['id']);

        if (!$accessToken) {
            return ['message' => Error::ACCESS_TOKEN_NOT_EXISTS];
        }

        // $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$accessToken.'&type=image'; // 添加临时素材
        // $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$accessToken; // 添加永久素材
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$accessToken.'&type=image'; // 新增其他类型永久素材

        $media = new \CURLFile($filePath);

        $result = Common::httpPost($url, ['media' => $media]);

        if (empty($result['media_id'])) {
            return ['message' => Error::UPLOAD_MATERIAL_FAIL];
        }
        // unlink('./uploads/material/' . $newName . '.' . $suffix);
        $result['host_url'] = 'https://'.config('app.app_host').'/uploads/material/' . $newName . '.' . $suffix;

        return $result;
    }

    // 公众号下拉列表
    public function getOfficialAccountSelect($userInfo)
    {
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getInfoById($cpsUserId, 'official_account_id');
            $ids = explode(',', $responsibilityPersonData['official_account_id']);
            $officialAccountData = $this->model->getDataByWhere(['id' => $ids], 'id, name');
            return $officialAccountData;
        }
        $id = $userInfo['cps_user_id'];
        $data = $this->responsibilityPersonModel->getInfoById($id, 'official_account_id');
        $ids = explode(',', $data['official_account_id']);
        $officialAccountData = $this->model->getDataByWhere(['id' => $ids], 'id, name');
        return $officialAccountData;
    }
}